/**
 * create by young (young2f@outlook.com) on 2020/9/16
 */


'use strict';
import React from 'react';
import {
  Button,
  DatePicker,
  Form,
  Input,
  InputNumber,
  notification,
  Popconfirm,
  Select, Switch,
  Table,
  Tag,
  TimePicker
} from 'antd';

import {FormField, FormLayout, ModalFooter, ModalView} from 'antd-extra';
import FormBase from '../../../components/Base/FormBase';
import moment from 'moment';
import 'moment/locale/zh-cn';
import {connect} from "dva";
import TextArea from "antd/es/input/TextArea";
import ViewTitle from "../../../components/ViewTitle";
import ModalCreateOrEditTask from "./ModalCreateOrEditTask";
import styles from "../../index.less";
import _ from "lodash";

moment.locale('zh-cn');

@Form.create()
@connect(({user, global, work}) => ({...user, ...work, ...global}))
export default class ModalCreateOrEditWorkTimer extends FormBase {
  constructor(props) {
    super(props);
    const {record} = props;
    this.state = {...record};
    const {workList = [], code = 'WRK' + moment().format('YYYYMMDDHHmmss')} = record;
    this.state.code = code;
    this.state.workList = workList;
  }

  componentDidMount() {
    this.props.dispatch({
      type: 'user/findUsers',
      payload: {table: 'users'}
    });
  }

  renderFoot = () => {
    const {foot, value, modalRef, callback, table, form} = this.props;
    if (foot) {
      return foot(value, modalRef);
    } else {
      return (
        <ModalFooter>
          <Button type="primary" onClick={() => {
            form.validateFields((err, values) => {
              if (err) {
                const {code} = err;
                const {errors} = code;
                errors.forEach(item => {
                  notification.error(item);
                });
                return;
              }
              const {workList = [], timerMethod} = this.state;
              values.workList = workList;
              values.timerMethod = timerMethod;
              callback(values);
              modalRef.close();
            });
          }}>确定</Button>
          <Button onClick={() => {
            modalRef.close();
          }}>取消</Button>
        </ModalFooter>
      );
    }
  };
  columns = () => {
    const temp = [];
    temp.push(
      {title: '任务编码', dataIndex: 'code', key: 'code'},
      {title: '创建人', dataIndex: 'createUsername', key: 'createUsername'},
      {title: '责任人', dataIndex: 'username', key: 'username'},
      {title: '线下人员姓名', dataIndex: 'offlineMan', key: 'offlineMan'},
      {title: '详细内容', dataIndex: 'desc', key: 'desc', ellipsis: true},
      {
        title: '要求完成时间',
        dataIndex: 'requiredCompletionDate',
        key: 'requiredCompletionDate',
        render: (text) => {
          return text ? <div>{moment(text).format('YYYY-MM-DD')}</div> : <div></div>;
        }
      },
      {
        title: '是否完成', dataIndex: 'isEnded', key: 'isEnded',
        render: (value, record) => {
          const {completionDate} = record;
          return completionDate ? <Tag color={'#0f0'}>是</Tag> : <Tag color={'#555'}>否</Tag>;
        }
      },
      {
        title: '操作', dataIndex: 'operation', key: 'operation',
        width: 220, fixed: 'right',
        render: (value, record) => {
          const {code} = record;
          return (
            <span>
                        {<a style={{marginRight: '6px'}}
                            onClick={() => this.onCreateOrEditTask(record)}
                        >编辑</a>}
              {<Popconfirm
                title="确认删除"
                onConfirm={() => {
                  const temp = [];
                  const {workList} = this.state;
                  _.map(workList, (item, index) => {
                    if (item.code !== code) {
                      temp.push(item);
                    }
                  });
                  this.state.workList = temp;
                  this.componentDidMount();
                }}
                okText="是"
                cancelText="否"
              >
                <a>删除</a>
              </Popconfirm>}
            </span>
          );
        }
      }
    );
    return temp;
  };

  onCreateOrEditTask = (values = {}) => {
    const {code, adminCode} = this.state;
    const login = this.getLoginInfo();
    const {username, isAdmin} = login;
    values.isTimer = true;
    const payload = this.props.form.getFieldsValue();
    _.map(payload, (value, key) => {
      if (value === '') {
        payload[key] = undefined;
      }
    });
    if (!values.code) {
      const {desc} = payload;
      values.desc = desc;
    }
    let {table} = this.props;
    ModalView.open(ModalCreateOrEditTask,
      {
        title: '分配任务',
        width: '1080px'
      }, {
        values, table,
        callback: (payload) => {
          payload.workCode = code;
          payload.adminCode = isAdmin ? code : adminCode;
          payload.createUsername = username;
          if (!values.code) {
            this.state.workList.push(payload);
            console.log('push', this.state.workList, payload);
            this.componentDidMount();
            return;
          }
          _.map(this.state.workList, (item, index) => {
            if (item.code === payload.code) {
              this.state.workList[index] = payload;
            }
          });
          this.componentDidMount();
        }
      });
  };

  getTimerDay() {
    const {timerDay = '周'} = this.state;
    const initValue = timerDay.includes("周") ? moment() : moment(timerDay);
    return <FormField
      label={'开始时间'}
      name={'timerDay'}
      initialValue={initValue}
    >
      <TimePicker format={"HH 点"} style={{width: '100%'}}></TimePicker>
    </FormField>;
  }

  getTimerWeek() {
    const {timerDay = '周一'} = this.state;
    const initValue = timerDay.includes("周") ? timerDay : '周一';
    return <FormField
      label={'开始时间'}
      name={'timerDay'}
      initialValue={initValue}
    >
      {/*<DatePicker picker="week"></DatePicker>*/}
      <Select style={{width: '100%'}} onSelect={v => {
        this.state.timerDay = v;
        this.componentDidMount();
      }}>
        {[
          <Select.Option value={'周一'}>{"周一"}</Select.Option>,
          <Select.Option value={'周二'}>{"周二"}</Select.Option>,
          <Select.Option value={'周三'}>{"周三"}</Select.Option>,
          <Select.Option value={'周四'}>{"周四"}</Select.Option>,
          <Select.Option value={'周五'}>{"周五"}</Select.Option>,
          <Select.Option value={'周六'}>{"周六"}</Select.Option>,
          <Select.Option value={'周日'}>{"周日"}</Select.Option>
        ]}
      </Select>
    </FormField>;
  }

  getTimerMonth() {
    const {timerDay = '周'} = this.state;
    const initValue = timerDay.includes("周") ? moment() : moment(timerDay);
    return <FormField
      label={'开始时间'}
      name={'timerDay'}
      initialValue={initValue}
    >
      <DatePicker format={"DD"} style={{width: '100%'}}></DatePicker>
    </FormField>;

  }

  getTimerYear() {
    const {timerDay = '周'} = this.state;
    const initValue = timerDay.includes("周") ? moment() : moment(timerDay);
    return <FormField
      label={'开始时间'}
      name={'timerDay'}
      initialValue={initValue}
    >
      <DatePicker format={"MM-DD"} style={{width: '100%'}}></DatePicker>
    </FormField>;

  }

  render() {
    let {form, footDisabled, style, record} = this.props;
    const {
      code, workName, rewardAmount = 0, punishAmount = 0,
      desc, memo, timerMethod, delayDay, isEnabled = true,
      workList = [], needConfirm
    } = this.state;

    const isEditable = this.getLoginInfo().isAdmin;
    return (
      <div style={{...style}}>
        <ViewTitle title={`${timerMethod}定时任务信息`}></ViewTitle>
        {<FormLayout form={form} cols={2}>
          <FormField
            label={'定时任务编码'}
            name={'code'}
            required={true}
            disabled={true}
            initialValue={code}
          >
            <Input disabled={true} style={{width: '100%'}}
            ></Input>
          </FormField>
          <FormField
            label={'定时任务名称'}
            name={'workName'}
            required={true}
            initialValue={workName}
          >
            <Input style={{width: '100%'}}
            ></Input>
          </FormField>

          <FormField
            label={'详细内容'}
            name={'desc'}
            initialValue={desc}
          >
            <TextArea disabled={!isEditable} style={{width: '100%'}}
            ></TextArea>
          </FormField>
          <FormField
            label={'处罚金额'}
            name={'punishAmount'}
            initialValue={punishAmount}
          >
            <InputNumber style={{width: '100%'}}
            ></InputNumber>
          </FormField>

          <FormField
            label={'奖励金额'}
            name={'rewardAmount'}
            initialValue={rewardAmount}
          >
            <InputNumber style={{width: '100%'}}
            ></InputNumber>
          </FormField>

          <FormField
            label={'备注'}
            name={'memo'}
            initialValue={memo}
          >
            <TextArea disabled={!isEditable} style={{width: '100%'}}
            ></TextArea>
          </FormField>
          <FormField
            label={'是否启用'}
            name={'isEnabled'}
            initialValue={isEnabled}
          >
            <Switch defaultChecked={isEnabled}
            ></Switch>
          </FormField>
          <FormField
            label={'是否需要手动确认'}
            name={'needConfirm'}
            initialValue={needConfirm}
          >
            <Switch defaultChecked={needConfirm}
            ></Switch>
          </FormField>
        </FormLayout>}
        {<ViewTitle title={`${timerMethod}定时时间设置`}></ViewTitle>}
        {<FormLayout form={form} cols={1}>
          {timerMethod === "每天" && this.getTimerDay()}
          {timerMethod === "每周" && this.getTimerWeek()}
          {timerMethod === "每月" && this.getTimerMonth()}
          {timerMethod === "每年" && this.getTimerYear()}
          <FormField
            label={'任务时长'}
            name={'delayDay'}
            initialValue={delayDay}
            required={true}
          >
            <InputNumber
              style={{width: '100%'}}
              formatter={value => `${value}天`}
              parser={value => value.replace('天', '')}
            ></InputNumber>
          </FormField>
        </FormLayout>
        }
        {<ViewTitle
          title={'责任人列表'}
          level={1}
          actions={<Button type={'primary'} onClick={() => {
            this.onCreateOrEditTask();
          }}>添加</Button>}
        ></ViewTitle>}
        {<Table
          className={styles.antTable}
          bordered={true}
          columns={this.columns()}
          dataSource={workList}
          // scroll={{x: true}}
          pagination={{
            current: this.state.current,
            total: this.state.total,
            showSizeChanger: true,
            onChange: page => {
              this.state.current = page;
              this.componentDidMount();
            },
            onShowSizeChange: (current, pageSize) => {
              this.state.current = 1;
              this.state.pageSize = pageSize;
              this.componentDidMount();
            }
          }}
        ></Table>}
        {!footDisabled && this.renderFoot()}
      </div>
    );
  }
}

